<?php

namespace addons\qingdongams\model;

use addons\qingdongams\library\StaffAuth;
use app\admin\controller\qingdongams\Base;
use app\admin\library\Auth;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use think\Db;
use think\Model;
use traits\model\SoftDelete;
use app\admin\model\Admin;

/**
 *员工表
 */
class Staff extends Model
{
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'qingdongams_staff';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'group_text',
    ];

    public static function getList($notInIds = [])
    {

        $where = ['status' => 1];
        if ($notInIds) {
            $where['id'] = ['not in', $notInIds];
        }
        return self::where($where)->field('id,name')->select();
    }

    //获取部门下 员工列表，树状结构
    public static function getDepartmentStaff($department, $name)
    {
        foreach ($department as $k => $v) {
            $v['staffs'] = self::getOneDepartmentStaffList($v['id'], $name);
            $v['count'] = count($v['staffs']);
            if ($v['children']) {
                $v['children'] = self::getDepartmentStaff($v['children'],$name);
            }
            $department[$k] = $v;
        }

        return $department;
    }

    //获取一个部门下 员工列表
    public static function getOneDepartmentStaffList($department_id, $name = '')
    {
        $where = ['department_id' => $department_id];
        if ($name) {
            $where['name'] = ['like', "%{$name}%"];
        }
        $staffs = self::where($where)->with(['parent'])
            ->field('id,name,post,department_id,parent_id,img,mobile')->select();
        $parents = [];
        $ids = [];
        foreach ($staffs as $v) {
            $ids[] = $v['id'];
        }
        foreach ($staffs as $v) {
            $parents[0][] = $v;
        }

        return self::getChilds($parents, 0);
    }

    //生成树状结构
    private static function getChilds($data, $pid)
    {
        $list = [];
        if (isset($data[$pid])) {
            $list = $data[$pid];
            foreach ($list as $k => $v) {
                $v['children'] = self::getChilds($data, $v['id']);
                $list[$k] = $v;
            }
        }

        return $list;
    }

    public static function getStaffCount($department)
    {
        foreach ($department as $k => $v) {
            $v['count'] = count($v['staffs']);
            if ($v['children']) {
                $v['count'] += self::getChildrenCount($v['children']);
                $v['children'] = self::getStaffCount($v['children']);
            }
            $department[$k] = $v;
        }
        return $department;
    }

    public static function getChildrenCount($children, $count = 0)
    {
        foreach ($children as $k => $v) {
            $count += count($v['staffs']);
            if ($v['children']) {
                $count += self::getChildrenCount($v['children']);
            }
        }
        return $count;
    }

    // 图片
    public static function getKeyList()
    {
        $staffs = self::where([])->field('id,name,img,group_ids')->select();
        $data = [];
        foreach ($staffs as $v) {
            $data[$v['id']] = $v;
        }
        return $data;
    }

    public static function getGroupStaffIds($group_id)
    {
        return self::where('', 'exp', Db::raw('FIND_IN_SET(' . intval($group_id) . ',group_ids)'))->column('id');
    }

    public static function getStaff()
    {
        return self::where([])->column('name', 'id');
    }

    public static function allList($notInIds = [])
    {
        $where['id'] = ['in', self::getMyStaffIds()];
        $where['status'] = 1;
        return self::where($where)->field('id,name')->select();
    }


    //员工业绩
    public static function getMyStaffIds()
    {
        $staff = self::info();
        $ids = [$staff->id];
        $l_ids = self::getLowerStaffId();
        $ids = array_merge($ids, $l_ids);

        return $ids;
    }

    //团队业绩
    public static function info()
    {
        if (StaffAuth::instance()->id) {
            return StaffAuth::instance();
        }
        $auth = new Auth();
        if ($auth->isLogin()) {
            $base = new Base();
            return $base->getStaff();
        }
        return null;
    }

    public static function getLowerStaffId()
    {
        $staff = self::info();
        $groupIds = AuthGroupAccess::where(['uid' => $staff->admin_id])->column('group_id');
        $role_type = StaffRole::where(['id' => $staff->role])->value('role_type');

        switch ($role_type) {
            case 1://本人
                $l_ids = [];
                break;
            case 2://本人及下属
                $l_ids = self::where([
                    'parent_id' => $staff->id,
                ])->column('id');
                break;
            case 3://本部门
                $uids = AuthGroupAccess::where(['group_id' => ['in', $groupIds]])->column('uid');
                $l_ids = self::where([
                    'admin_id' => ['in', $uids],
                    'status' => 1,
                    'id' => ['neq', $staff->id]
                ])->column('id');
                break;
            case 4://仅下属部门
                $groupIds = self::getLowerId($groupIds, false);
                $uids = AuthGroupAccess::where(['group_id' => ['in', $groupIds]])->column('uid');
                $l_ids = self::where([
                    'admin_id' => ['in', $uids],
                    'status' => 1,
                    'id' => ['neq', $staff->id]
                ])->column('id');
                break;
            case 5://本部门及下属部门
                $groupIds = self::getLowerId($groupIds, true);
                $uids = AuthGroupAccess::where(['group_id' => ['in', $groupIds]])->column('uid');
                $l_ids = self::where([
                    'admin_id' => ['in', $uids],
                    'status' => 1,
                    'id' => ['neq', $staff->id]
                ])->column('id');
                break;
            case 6://全部
                $l_ids = self::where([
                    'status' => 1,
                    'id' => ['neq', $staff->id]
                ])->column('id');
                break;
        }
        if (empty($l_ids)) {//返回空 下属查询 会查询全部
            return ['-1'];
        }
        return $l_ids;
    }

    //绑定admin账号
    public static function getLowerId($l_ids, $top = true)
    {
        if (!is_array($l_ids)) {
            $l_ids = explode(',', $l_ids);
        }
        $ids = AuthGroup::where(['pid' => ['in', $l_ids]])->column('id');
        if ($ids) {
            $w_ids = self::getLowerId($ids, false);
            $ids = array_merge($ids, $w_ids);
        } else {
            $ids = [];
        }
        if ($top) {
            $ids = array_merge($ids, $l_ids);
        }
        return array_unique($ids);
    }

    //角色

    /**
     * 获取权限列表
     */
    public static function getStaffRule($type)
    {
        $row = StaffRule::where(['name' => $type])->find();
        if (!$row) {
            return [];
        }
        $rules = StaffRule::where(['pid' => $row->id])->column('name', 'id');
        $staff = self::info();
        $staffRules = StaffRole::where(['id' => $staff->role])->value('rules');
        $staffRules = explode(',', $staffRules) ?? [];
        $value = [];
        foreach ($staffRules as $r) {
            if (isset($rules[$r])) {
                $value[] = $rules[$r];
            }
        }
        return $value;
    }

    //上级
    public static function getOneGroupStaffIds($department_id, $name = '')
    {
        $where = [];
        if ($name) {
            $where['name'] = ['like', "%{$name}%"];
        }
        $department_id = intval($department_id);
        $ids = self::where($where)
            ->where('', 'exp', "FIND_IN_SET({$department_id},group_ids)")
            ->column('id');
        return $ids;
    }

    //获取员工
    protected static function init()
    {
        self::beforeInsert(function ($row) {
            $changed = $row->getChangedData();
            $admin = [
                'username' => $changed['mobile'],
                'nickname' => $changed['name'],
                'password' => $changed['password'],
                'salt' => $changed['salt'],
                'avatar' => $changed['img'],
                'email' => rand(111111111,999999999).'@163.com',
            ];
            if (isset($changed['admin_id']) && $changed['admin_id']) {
                return true;
            }
            $adminModel = new Admin();
            $result = $adminModel->validate('Admin.add')->save($admin);
            if ($result == false) {
                exception($adminModel->getError());
            }
            $row->admin_id = $adminModel->getLastInsID();

            $group = explode(',', $changed['group_ids']);
            foreach ($group as $value) {
                $dataset[] = ['uid' => $row->admin_id, 'group_id' => $value];
            }
            model('AuthGroupAccess')->saveAll($dataset);

            return $row;
        });

        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            if (!isset($row->id)) {
                return true;
            }
            $staff = self::get($row->id);
            if (empty($staff->admin_id)) {
                return $row;
            }
            //admin用户不更新
            if ($staff->admin_id == 1) {
                return true;
            }
            if (isset($changed['deletetime']) && $changed['deletetime']) {
                Admin::where(['id' => $staff->admin_id])->delete();
                return true;
            }
            if (isset($changed['mobile']) || isset($changed['name'])
                || isset($changed['email']) || isset($changed['img'])) {
                $params = [];
                if (isset($changed['mobile'])) {
                    $params['username'] = $changed['mobile'];
                }
                if (isset($changed['name'])) {
                    $params['nickname'] = $changed['name'];
                }
                if (isset($changed['img'])) {
                    $params['avatar'] = $changed['img'];
                }
                if (isset($changed['email'])) {
                    $params['email'] = $changed['email'];
                }
                //如果有修改密码
                if (isset($changed['password'])) {
                    if ($changed['password']) {
                        $params['password'] = $changed['password'];
                        $params['salt'] = $changed['salt'];
                    }
                }

                $adminModel = new Admin();
                $result = $adminModel->save($params, ['id' => $staff->admin_id]);
                if ($result === false) {
                    exception($row->getError());
                }
            }

            if (isset($changed['group_ids'])) {
                // 先移除所有权限
                model('AuthGroupAccess')->where('uid', $staff->admin_id)->delete();
                $group = explode(',', $changed['group_ids']);
                foreach ($group as $value) {
                    $dataset[] = ['uid' => $staff->admin_id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);

            }

            return $row;
        });

    }

    //包含当前角色
    public function getGroupTextAttr($value, $data)
    {
        if (!isset($data['group_ids'])) {
            return '';
        }
        $names = AuthGroup::where(['id' => ['in', $data['group_ids']]])->column('name');
        return implode(',', $names);
    }

    //获取下属员工IDs
    public function getImgAttr($value)
    {
        if ($value) {
            return cdnurl($value, true);
        } else {
            return $value;
        }
    }

    //获取全部ID
    public function getCreatetimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    public function achievement()
    {
        return $this->belongsTo(Achievement::class, 'id', 'obj_id')->where(['type' => 3]);
    }

    public function teamAchievement()
    {
        $condition['type'] = ['in', [2, 4]];
        return $this->belongsTo(Achievement::class, 'id', 'obj_id')->where($condition);
    }

    public function department()
    {
        return $this->belongsTo(StaffDepartment::class, 'department_id', 'id')->field('id,name as department_name')->bind('department_name');
    }

    //获取自己及下属员工
    public function admin()
    {
        return $this->belongsTo(Admin::class, 'admin_id', 'id')->field('id,username');
    }

    public function staffrole()
    {
        return $this->hasOne(StaffRole::class, 'id', 'role')->field('id,name');
    }

    //获取一个部门下 员工列表
    public function parent()
    {
        return $this->belongsTo(Staff::class, 'parent_id', 'id')->field('id,name as parent_name')->bind('parent_name');
    }

    //客户
    public function customer()
    {
        return $this->belongsTo(Customer::class, 'id', 'create_staff_id')->group('create_staff_id')->field('create_staff_id,count(*) as achieve')->bind('achieve');
    }
    //拜访
    public function visit()
    {
        return $this->belongsTo(Event::class, 'id', 'staff_id')->group('staff_id')->field('staff_id,count(*) as achieve')->where(['type' => 3, 'status' => 2])->bind('achieve');
    }

    //回款
    public function receivables()
    {
        return $this->belongsTo(Receivables::class, 'id', 'create_staff_id')->where(['check_status' => 2])->group('create_staff_id')->field('create_staff_id,sum(money) as achieve')->bind('achieve');
    }

    //工单
    public function workorder()
    {
        return $this->belongsTo(Workorder::class, 'id', 'owner_staff_id')->group('owner_staff_id')->field('owner_staff_id,count(*) as achieve')->bind('achieve');
    }

    //订单
    public function contract()
    {
        return $this->belongsTo(Contract::class, 'id', 'create_staff_id')->where(['check_status' => 2])->group('create_staff_id')->field('create_staff_id,sum(money) as achieve')->bind('achieve');
    }

}
